<template>
    <c-dialog v-model:show="dialogFlag" v-if="dialogFlag" :title="title" @confirm="save" @close="close" :width="630">
        <el-form ref="ruleFormRef" :rules="rules" :model="formdata" label-width="80px" size="small">
            <el-form-item label="所属公司" prop="companyId" v-if="!editData.userId">
                <company-select v-model="formdata.companyId" @change="setFarmData" :disabled="userStore.userInfo.roleId!=1"/>
            </el-form-item>
            <el-form-item label="姓名" prop="realName">
                <el-input v-model="formdata.realName" placeholder="请输入姓名"/>
            </el-form-item>
            <el-form-item label="账号" prop="phone">
                <el-input v-model="formdata.phone" placeholder="请输入手机号"/>
            </el-form-item>
            <el-form-item label="选择添加" prop="">
                <div style="display: flex; width:100%">
                    <div style="flex: 1;">
                        <farm-select v-show="formdata.companyId" ref="farmRef" v-model="formdata.farmId" :params="{companyId:formdata.companyId,isEnable:true}" @change="o=>curFarmItem=o"/>
                        <el-select v-if="!formdata.companyId" disabled placeholder="请选择农场" style="width:100%"></el-select>
                    </div>
                    <div style="flex: 1; margin:0 5px">
                        <team-role-select v-model="formdata.roleId" @onChange="o=>curRoleItem=o"/>
                    </div>
                    <div>
                        <el-button type="success" class="myBtn" plain @click="addSelect">添加</el-button>
                    </div>
                </div>
            </el-form-item>
            <el-form-item label="" prop="tableData">
                <div class="addtips">提示：选择农场和角色为该账号添加农场角色，一个账号可以在不同的农场下担任不同的角色。</div>
                <table class="itemTableBox" style="width:100%;min-width:100%;margin:10px 0;">
                    <tr>
                        <th width="30" style="text-align: center">序号</th>
                        <th>农场名称</th>
                        <th>角色</th>
                        <th width="50" style="text-align: center">操作</th>
                    </tr>
                    <tr v-for="(dt,index) in tableData" :key="index">
                        <td style="text-align: center">{{index + 1}}</td>
                        <td>{{dt.farmName}}</td>
                        <td>{{dt.roleName}}</td>
                        <td>
                            <div class="tbItemFlex">
                                <el-icon color="#f82e2e" :size="20" @click="tableData.splice(index,1)"><Remove /></el-icon>
                            </div>
                        </td>
                    </tr>
                </table>
            </el-form-item>
        </el-form>
    </c-dialog>
</template>
<script setup>
import { ref,onMounted,reactive } from 'vue';
import {addTeam,editTeam,getTeamDetail} from '@/api/system'
import cDialog from '@/components/custom/cDialog.vue'
import { message } from '@/utils/element'
import { ElMessageBox } from 'element-plus'
import companySelect from '@/components/custom/companySelect.vue'
import farmSelect from '@/components/custom/farmSelect.vue'
import teamRoleSelect from '@/components/custom/teamRoleSelect.vue'
import { useUserStore } from '@/pinia/modules/user'

const userStore = useUserStore()

const props = defineProps({
    show: {
        type: Boolean,
        default: false
    },
    title: String,
    editData: Object,
    type:Number // 操作类型：1为新增，2为编辑，3为查看
})
const emit = defineEmits(['update:show','success'])

const formdata = ref({})
const ruleFormRef = ref(null)
const farmRef = ref(null)
const tableData = ref([])
const curFarmItem = ref('')
const curRoleItem = ref('')

// 验证手机号
const checkPhone = (rule, phone, callback) => {
      const myreg = /^[1][3,4,5,7,8,9][0-9]{9}$/;
      if (!myreg.test(phone)) {
          return callback(new Error('手机号输入有误'))
      } else {
          callback() // 验证通过
      }
  }
const rules = reactive({
    companyId: [
        { required: true, message: '请选择所属公司', trigger: 'blur' },
        //{ min: 3, max: 50, message: 'Length should be 3 to 5', trigger: 'blur' },
    ],
    realName:[
        { required: true, message: '请输入姓名', trigger: 'blur' },
    ],
    phone:[
        { required: true, message: '请输入手机号', trigger: 'blur' },
        { validator:checkPhone, trigger: 'blur' }
    ],
    tableData:[
        { validator:(rule, value, callback)=>{
            if(tableData.value.length<1){
                return callback(new Error('请添加农场和角色'))
            }else {
                callback() // 验证通过
            }
        }, trigger: 'blur' }
    ],
    // roleName:[
    //     { required: true, message: '请选择角色名称', trigger: 'blur' },
    // ]
  })


onMounted(async ()=>{
    formdata.value.companyId = userStore.userInfo.companyId
    if(props.editData.userId){ // 编辑
        const res = await getTeamDetail({userId:props.editData.userId})
        tableData.value = res.data
        formdata.value.companyId = props.editData.companyId
        formdata.value.realName = props.editData.realName
        formdata.value.phone = props.editData.phone
       // formdata.value.farmId = props.editData.farmId
        //formdata.value.roleName = props.editData.roleName
    }
})


const dialogFlag = ref(props.show)

const addSelect = ()=>{
    if(!formdata.value.farmId || !formdata.value.roleId){
        return message('请选择农场和角色',3)
    }

    let flag = false
    tableData.value.forEach(item =>{
        if(item.teamRoleId == formdata.value.roleId && item.farmId == formdata.value.farmId){
            flag = true
        }
    })
    if(flag){
        return message('不能重复添加',3)
    }
    tableData.value = [...tableData.value,{...curFarmItem.value,...curRoleItem.value}]
    curFarmItem.value = ''
    curRoleItem.value = ''
    formdata.value.farmId = ''
    formdata.value.roleId = ''
}

const save = async() => {
    await ruleFormRef.value.validate(async(valid, fields) => {
        if (valid) {
            let usersFarms = []
            tableData.value.forEach(item =>{
                const obj = {
                    "farmId": item.farmId,
                    "roleName": item.roleName,
                    "teamRoleId": item.teamRoleId
                }
                usersFarms.push(obj)
            })

            let res = {}
            let params = {
                "companyId": formdata.value.companyId,
                "phone": formdata.value.phone,
                "realName": formdata.value.realName,
                "usersFarms": usersFarms
            }
            if(props.editData.userId){
                res = await editTeam({...params,"userId": props.editData.userId,"userName": props.editData.userName,})
            }else{
                res= await addTeam(params)
            }
            if(res.code ==0){
                message('数据提交成功',2)
                emit('success')
                close()
            }else{
                message(res.message,3)
            }
        } 
    })
}

const setFarmData = (id)=>{
    farmRef.value.getTableData({companyId:id}) // 获取数据
}

const close = () => {
    emit('update:show', false)
}
</script>
<style lang="scss" scoped>
    .addtips{
        font-size: 11px; 
        color:#999;
        line-height: normal;
        margin: -2px 0 0 0;
    }
    .itemTableBox{
        width: 100%;
        min-width: 1150px;
        border: 1px solid #ebeef5;
        border-collapse:collapse ;
        th,td{
            text-align: left; 
            span{
                color: #f70808;
            }
        }
        th{
            background-color: #f5f7fa;
            height: 30px;
            padding: 0 8px;
            &+th{
                border-left: 1px solid #ebeef5;
            }
        }
        td{
            text-align: left;
            padding:6px 8px;
            border-top: 1px solid #ebeef5;
            &+td{
                border-left: 1px solid #ebeef5;   
            }
            
        }
        .tbItemFlex{
            display: flex;
            align-items: center;
            justify-content: center;
            .el-icon{
                cursor: pointer;
                &:hover{

                }
            }
        }
    }
</style>
